import {ElMessage} from 'element-plus';
import Login from '@/components/Login.vue'
import {checkLogin} from "@/api/index.js";
import {createRouter, createWebHashHistory} from "vue-router";


const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: 'login',
            meta: { title: '登录' },
            component: Login
        },
    ]
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    if (whiteList.includes(to.path)) {
        next()
    } else if (!token) {
        ElMessage.error('请先登录')
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    } else {
        checkLogin().then(() => {
            next()
        })
    }
})

export default router